﻿using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Forms;
using SampleCode.VirtualFS.ViewModel;
using MessageBox = System.Windows.MessageBox;
using OpenFileDialog = Microsoft.Win32.OpenFileDialog;
using SaveFileDialog = Microsoft.Win32.SaveFileDialog;
using TextBox = System.Windows.Controls.TextBox;

namespace SampleCode.VirtualFS.WPFApp
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public MainWindow()
        {
            InitializeComponent();

            // Initializing the DataContext with a new ViewModel
            var diskVM = new FsDiskViewModel(Dispatcher);
            diskVM.DiskCreated += () => VisualStateManager.GoToElementState(grid, "NoFileOpened", true);
            DataContext = diskVM;
        }

        /// <summary>
        /// INotifyPropertyChanged implementation
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// A helper property, that shows if a folder is selected
        /// </summary>
        public bool IsFolderSelected
        {
            get
            {
                return treeFolders.SelectedItem != null;
            }
        }

        /// <summary>
        /// A helper property, that shows if a file is selected
        /// </summary>
        public bool IsFileSelected
        {
            get
            {
                return listFiles.SelectedItem != null;
            }
        }

        private void btnOpenFS_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            var dlg = new OpenFileDialog
            {
                Title = "Select an existing VirtualFS file to open"
            };
            if (dlg.ShowDialog() != true)
                return;

            ((FsDiskViewModel)DataContext).OpenDiskCommand.Execute(dlg.FileName);
        }

        private void btnNewFS_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            var dlg = new SaveFileDialog
            {
                Title = "Specify a name for the newly created VirtualFS file"
            };
            if (dlg.ShowDialog() != true)
                return;

            ((FsDiskViewModel)DataContext).CreateDiskCommand.Execute(dlg.FileName);
        }
		
        private void TextBoxIsVisibleChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e)
        {
            if(!(bool)e.NewValue) return;

			TextBoxLoaded(sender, null);
        }

        private void TextBoxLoaded(object sender, System.Windows.RoutedEventArgs e)
        {
            var txtBox = sender as TextBox;
            if ((txtBox == null) || (txtBox.Visibility != Visibility.Visible)) return;
            txtBox.Focus();
        }		
		
        private void btnOpenFile_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            var fileVM = listFiles.SelectedItem as FsFileViewModel;
            if (fileVM == null) return;

            fileVM.OpenFileCommand.Execute(null);

            gridMain.IsEnabled = false;
            gridToolbar.IsEnabled = false;
            VisualStateManager.GoToElementState(grid, "FileOpened", true);
        }

        private void btnCloseFile_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            VisualStateManager.GoToElementState(grid, "NoFileOpened", true);
            gridMain.IsEnabled = true;
            gridToolbar.IsEnabled = true;

            var fileVM = listFiles.SelectedItem as FsFileViewModel;
            if (fileVM == null) return;

            fileVM.CloseFileCommand.Execute(null);
        }

        private void treeFolders_SelectedItemChanged(object sender, System.Windows.RoutedPropertyChangedEventArgs<object> e)
        {
            OnPropertyChanged("IsFolderSelected");

            // we need to switch off the Finder mode, if it was on
            var oldFolderVM = e.OldValue as FsFolderViewModel;
            if (oldFolderVM == null) return;

            oldFolderVM.SearchOffCommand.Execute(null);
        }

        private void listFiles_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            OnPropertyChanged("IsFileSelected");
        }

        /// <summary>
        /// Raises this object's PropertyChanged event.
        /// </summary>
        /// <param name="propertyName">The property that has a new value.</param>
        protected virtual void OnPropertyChanged(string propertyName)
        {
            // for not to be afraid of multi-threading
            var handler = PropertyChanged;
            if (handler == null) return;

            handler(this, new PropertyChangedEventArgs(propertyName));
        }

        private void btnImportFS_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            var folderVM = treeFolders.SelectedItem as FsFolderViewModel;
            if (folderVM == null)
                throw new InvalidOperationException("No folder is currently selected in the tree!");

            var dlg = new OpenFileDialog { Title = "Select a VirtualFS file to import from" };
            if (dlg.ShowDialog() != true)
                return;

            folderVM.ImportFSCommand.Execute(dlg.FileName);
        }

        private void btnImportFolder_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            var folderVM = treeFolders.SelectedItem as FsFolderViewModel;
            if (folderVM == null)
                throw new InvalidOperationException("No folder is currently selected in the tree!");

            var dlg = new FolderBrowserDialog { Description = "Select a physical folder to be imported" };
            if (dlg.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                return;

            folderVM.ImportFolderCommand.Execute(dlg.SelectedPath);
        }

        private void btnExportFolder_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            var folderVM = treeFolders.SelectedItem as FsFolderViewModel;
            if (folderVM == null)
                throw new InvalidOperationException("No folder is currently selected in the tree!");

            var dlg = new FolderBrowserDialog { Description = "Select a physical folder to make export to" };
            if (dlg.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                return;

            folderVM.ExportFolderCommand.Execute(dlg.SelectedPath);
        }

        private void btnThreadTest_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            var diskVM = DataContext as FsDiskViewModel;
            if (diskVM == null) return;

            diskVM.ThreadTestCommand.Execute(null);
        }

        private void Window_Closed(object sender, System.EventArgs e)
        {
            var diskVM = DataContext as FsDiskViewModel;
            if(diskVM != null)
                diskVM.Dispose();
        }

        private void window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            // checking if no async operations is started

            var diskVM = DataContext as FsDiskViewModel;
            if 
            (
                (diskVM == null) 
                ||
                (diskVM.AsyncOperationsEnabled)
            )
                return;

            MessageBox.Show("Please, wait till asynchronous operation is finished!");
            e.Cancel = true;
        }
    }
}
